package datastructure.stackAndQueue;


public class LinkedStack implements Stack {
	//Inner class
	
	private static class SLLNode {
		Object data;
		SLLNode next;
		
		SLLNode(){}
		
		SLLNode(Object obj){
			data = obj;
		}
		
		SLLNode(Object obj,SLLNode link){
			data = obj;
			next = link;
		}
		
		public String toString(){
			return data.toString();
		}
	}
	
	private SLLNode top;
	private int count;
	
	LinkedStack(){
		clear();
	}
	

	@Override
	public void clear() {
		top = null;
		count = 0;
	}

	@Override
	public boolean isEmpty() {
		return count == 0;
	}

	@Override
	public Object peek() {
		if(count==0){
			try {
				throw new IllegalStackException();
			} catch (IllegalStackException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
		}
		return top.data;
	}

	@Override
	public Object pop() {
		if(count==0){
			try {
				throw new IllegalStackException();
			} catch (IllegalStackException e) {
				e.printStackTrace();
			}
		}
		count--;
		Object val = top.data;
		top = top.next;
		return val;
	}

	public void push(Object val) {
		top = new SLLNode(val,top);
		count++;
	}

	public int size() {
		return count;
	}

	public String toString(){
		StringBuffer buf = new StringBuffer("[");
		
		for(SLLNode node = top; node != null;){
			buf.append(node.toString());
			if((node=node.next)!=null){
				buf.append(",");
			}else{
				buf.append("]");
				break;
			}
		}
		return buf.toString();
	}

}
